import json
import os
import threading
import time
from urllib import parse

from flask import Flask, request

from FaceRec.FaceRec.App_Faces import check as check_fr
from FaceRec.FaceRec.App_Faces import recognize, locate, add, delete, query, reload, camera, camera2
from FaceRec.FaceRec.VideoTest import snap_per_seconds
from FaceRec.FaceRec.cfg_FR import save_path
from FaceRec.FaceRec.utils_FR import file_request
from MotionDet.App_Motion import convert as convert_md
from PedestrianDet.App_Pedestrian import check as check_pd

app = Flask(__name__)


@app.route('/imr-ai-service/pedestrian/check/<file_id>', methods=['POST'])
def check_pedestrian(file_id):
    result = check_pd(file_id)
    return result


@app.route('/imr-ai-service/motion_detection/convert', methods=['POST'])
def convert():
    result = convert_md()
    return result


@app.route('/imr-ai-service/face_features/check/<file_id>', methods=['POST'])
def check_face(file_id):
    result = check_fr(file_id)
    return result


@app.route('/imr-ai-service/face_features/recognize/<file_id>', methods=['POST'])
def recognize_face(file_id):
    result = recognize(file_id)
    return result


@app.route('/imr-ai-service/face_features/locate/<file_id>', methods=['POST'])
def locate_face(file_id):
    result = locate(file_id)
    return result


@app.route('/imr-ai-service/face_features/add/<file_id>', methods=['POST'])
def add_face(file_id):
    result = add(file_id)
    return result


@app.route('/imr-ai-service/face_features/delete/<file_name>', methods=['POST'])
def delete_face(file_name):
    result = delete(file_name)
    return result


@app.route('/imr-ai-service/face_features/query', methods=['POST'])
def query_face():
    result = query()
    return result


@app.route('/imr-ai-service/face_features/reload', methods=['POST'])
def reload_face():
    result = reload()
    return result


@app.route('/imr-ai-service/face_features/camera_recognize', methods=['POST'])
def camera_face():
    result = camera()
    return result


@app.route('/imr-ai-service/face_features/door_open', methods=['POST'])
def door_open():
    result = camera2()
    return result


@app.route('/imr-ai-service/atomic_functions/snapshot', methods=['POST'])
def snapshot():
    if request.method == "POST":
        c_da = request.data
        data = json.loads(c_da.decode())
        multiple_mode = 'multiple' in data
        multiple_mode = multiple_mode and 'cephId' in data
        multiple_mode = multiple_mode and data['multiple'] is not None
        multiple_mode = multiple_mode and data['cephId'] is not None
        if multiple_mode:
            print('连续截图模式启动.')
            multiple = data['multiple']
            file_name = file_request('query', data['cephId'])
            rtsp_address = os.path.join(save_path, file_name)
        else:
            multiple = None
            rtsp_address = data['RTSP_ADDR']
            assert type(rtsp_address) is str
            rtsp_address = rtsp_address.replace('+', parse.quote('+'))
        try:
            resize = data['resize']
        except Exception as e:
            print(repr(e))
            resize = True

        time_take = time.time()
        if multiple_mode:
            t_snap = threading.Thread(
                target=snap_per_seconds,
                args=(
                    rtsp_address,
                    resize,
                    multiple,
                    multiple_mode,
                    data
                )
            )
            t_snap.start()
            result = '异步处理（回调）模式'
            result = result.encode()
        else:
            result = snap_per_seconds(
                rtsp_address=rtsp_address,
                resize=resize,
                multiple=multiple,
                multiple_mode=multiple_mode,
                data=data
            )
        time_take = time.time() - time_take

        ret = (result is not None)
        msg = {True: "成功", False: "失败"}
        if ret:
            result = result.decode()
        output = json.dumps(
            {
                'ret': ret,
                'msg': msg[ret],
                'result': result,
                'timeTake': round(time_take, 4)
            },
            ensure_ascii=False
        )
        return output


if __name__ == '__main__':
    pid = os.getpid()
    print('pid is:', pid)
    with open('app_pid.txt', 'w') as f:
        f.writelines([str(pid)])
    app.run(
        host="0.0.0.0",
        port=int("20290"),
        debug=False, threaded=True
    )
